#include "ScalarStorage.h"
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include "logger.h"
ScalarStorage::ScalarStorage(const std::string& path)
{
    // 创建数据库
    rocksdb::Options options;  
    options.create_if_missing = true;  
    rocksdb::Status status = rocksdb::DB::Open(options, path, &db);
    if(!status.ok()){
        throw std::runtime_error("Failed to open rocksdb: " + status.ToString());
    }
}

ScalarStorage::~ScalarStorage()
{
    delete db;
}

void ScalarStorage::insert_scalar(uint64_t id,const rapidjson::Document& data){
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    data.Accept(writer);
    std::string value = buffer.GetString();

    rocksdb::Status status = db->Put(rocksdb::WriteOptions(),std::to_string(id),value);
    if(!status.ok()){
        GlobalLogger->error("Failed to insert scalar: {}",status.ToString());
    }
}

rapidjson::Document ScalarStorage::get_scalar(uint64_t id)
{
    std::string value;
    rocksdb::Status status;
    try{
        status = db->Get(rocksdb::ReadOptions(),std::to_string(id),&value);
    }catch(std::exception& e){
        GlobalLogger->error("Failed to get scalar: {}",e.what());
    }
    
    if(!status.ok()){
        GlobalLogger->error("Failed to get scalar: {}",status.ToString());
        return rapidjson::Document();
    }
    rapidjson::Document doc;
    doc.Parse(value.c_str());

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);
    GlobalLogger->debug("Data retrieved from ScalarStorage: {}, RocksDB status: {}", buffer.GetString(), status.ToString());
    return doc;
}

void ScalarStorage::put(const std::string& key, const std::string& value){
    rocksdb::Status status = db->Put(rocksdb::WriteOptions(), key, value);
    if(!status.ok()){
        GlobalLogger->error("Failed to put key-value pair: {}", status.ToString());
    }
}

std::string ScalarStorage::get(const std::string& key){
    std::string value;
    rocksdb::Status status=db->Get(rocksdb::ReadOptions(), key,&value); 
    if(!status.ok()){
        GlobalLogger->error("Failed to get value for key: {}", status.ToString());
        return "";
    }
    return value;
}